package com.yunxiao.cloud.oss.config;

import com.yunxiao.cloud.oss.hdfs.HadoopClient;
import com.yunxiao.cloud.oss.property.HadoopProperties;
import org.apache.hadoop.fs.FileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;
import java.net.URI;


/**
 * @description: HadoopConfig
 * @date: 2019/12/18 10:04
 * @author: yunxiao
 * @version: 1.0
 */
@Configuration
@ConditionalOnProperty(name = "hadoop.name-node")
public class HadoopConfig {
    private static final Logger logger = LoggerFactory.getLogger(HadoopConfig.class);

    @Value("${hadoop.name-node}")
    private String nameNode;
    @Value("${hadoop.user}")
    private String hadoopUser;

    @Bean
    public FileSystem fs() {
        FileSystem fileSystem = null;
        org.apache.hadoop.conf.Configuration configuration = new org.apache.hadoop.conf.Configuration();
        try {
            URI uri = new URI(nameNode);
            fileSystem = FileSystem.get(uri, configuration, hadoopUser);
        } catch (Exception e) {

            logger.error("【FileSystem配置初始化失败】", e);
        }
        return fileSystem;
    }

    @Bean
    @ConditionalOnBean(FileSystem.class)
    public HadoopClient hadoopClient(FileSystem fileSystem, HadoopProperties hadoopProperties) {
        return new HadoopClient(fileSystem, hadoopProperties);
    }

    /**
     * 文件上传配置
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  单个数据大小
        factory.setMaxFileSize(DataSize.ofGigabytes(100));
        /// 总上传数据大小
        factory.setMaxRequestSize(DataSize.ofGigabytes(100));
        return factory.createMultipartConfig();
    }

}
